package example;

import example.entity.User;
import example.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author 张心怡
 * @date 2024/12/16
 */
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("path");
        if (action == null) {
            // 如果没有action参数，默认执行查询所有书籍信息的操作，并设置一个标志
            action = "login";
        }
        switch (action) {
            case "login": {
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                String type = request.getParameter("type");
                User login = UserService.login(username, password, Integer.parseInt(type));
                if (login != null) {
                    request.getSession().setAttribute("user", login);
                    response.sendRedirect("adminDashboardServlet");
                } else {
                    request.setAttribute("msg", "登录失败！");
                    request.getRequestDispatcher("/login.jsp").forward(request, response);
                }
                break;
            }
            case "getUsersByName": {
                String username = request.getParameter("name");
                List<User> allUsers = UserService.getAllUsers(username);
                request.setAttribute("users", allUsers);
                request.getRequestDispatcher("/manageUsers.jsp").forward(request, response);
                break;
            }
            case "signUp": {
                String username = request.getParameter("username");
                User userByUsernameOrEmail = UserService.getUserByUsername(username);
                if (userByUsernameOrEmail == null) {
                    String password = request.getParameter("password");
                    String email = request.getParameter("email");
                    User user = new User(username, password, email);
                    UserService.signUp(user);
                    request.setAttribute("msg", "注册成功！账号为：" + username + "，密码为：" + password);
                    request.getRequestDispatcher("/login.jsp").forward(request, response);
                } else {
                    request.setAttribute("msg", "用户名已存在，请重新注册！");
                    request.getRequestDispatcher("/signUp.jsp").forward(request, response);
                }
                break;
            }
            case "findPassword": {
                String username = request.getParameter("username");
                String email = request.getParameter("email");
                User user = UserService.getUserByUsernameAndEmail(username, email); // 假设存在根据用户名或邮箱查找用户的方法
                if (user != null) {
                    // 这里可以生成一个临时密码或发送密码重置链接到用户邮箱
                    // 为了简单起见，这里只是模拟生成一个临时密码并将其设置为用户密码（实际应用中应避免这种简单处理）
                    String temporaryPassword = "123456"; // 生成临时密码逻辑
                    user.setPassword(temporaryPassword);
                    UserService.updatePassWord(user); // 更新用户密码
                    request.setAttribute("msg", "密码已重置为：" + temporaryPassword + "，请使用该密码登录并及时修改。");
                    request.getRequestDispatcher("login.jsp").forward(request, response);
                } else {
                    request.setAttribute("msg", "用户名或邮箱不存在，请检查后重试。");
                    request.getRequestDispatcher("find_password.jsp").forward(request, response);
                }
                break;
            }
            case "delete": {
                String id = request.getParameter("id");
                UserService.delete(Integer.parseInt(id));
                request.setAttribute("msg", "删除成功。");
                request.getRequestDispatcher("userServlet?path=getUsersByName").forward(request, response);
                break;
            }
            case "getById": {
                String id = request.getParameter("id");
                if (id != null && !id.isEmpty()) {
                    User byId = UserService.getById(Integer.parseInt(id));
                    request.setAttribute("editMode", true);
                    request.setAttribute("user", byId);
                } else {
                    request.setAttribute("editMode", false);
                }
                request.getRequestDispatcher("addEditUser.jsp").forward(request, response);
                break;
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String type = request.getParameter("type");

        User userByUsernameOrEmail = UserService.getUserByUsername(username);
        if (userByUsernameOrEmail == null) {
            // 创建用户对象并设置属性
            User user = new User();
            user.setUsername(username);
            user.setEmail(email);
            user.setPassword(password);
            user.setType(Integer.parseInt(type));
            // 调用数据访问层方法插入用户
            if (id != null && !id.isEmpty()) {
                user.setId(Integer.parseInt(id));
                UserService.updateUser(user);
            } else {
                UserService.addUser(user);
            }

            // 添加成功后，重定向到管理用户页面
            response.sendRedirect("userServlet?path=getUsersByName");
        } else {
            request.setAttribute("msg", "用户名已存在");
            request.getRequestDispatcher("addEditUser.jsp").forward(request, response);
        }
    }
}
